package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"mall/service/mqueue/common/types"
	"mall/service/mqueue/job/internal/svc"
	"mall/service/product/rpc/productclient"

	"github.com/hibiken/asynq"
)

// DeferedStockSubtractRevertProcessor implements asynq.Handler interface.
type DeferedStockSubtractRevertProcessor struct {
	svcCtx *svc.ServiceContext
}

func NewDeferedStockSubtractRevertProcessor(svcCtx *svc.ServiceContext) *DeferedStockSubtractRevertProcessor {
	return &DeferedStockSubtractRevertProcessor{
		svcCtx: svcCtx,
	}
}

// defer revert failed order stock : if return err != nil, asynq will retry
func (l *DeferedStockSubtractRevertProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
	var p types.DeferedStockSubtractRevertPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("DeferedStockSubtractRevertProcessor payload json.Unmarshal fail: %+v : %w", err, asynq.SkipRetry)
	}

	if len(p.Stocks) == 0 {
		return nil
	}

	var stocks []*productclient.ProductVariationStock
	for _, v := range p.Stocks {
		if v.Id > 0 && v.Stock > 0 {
			stocks = append(stocks, &productclient.ProductVariationStock{
				Id:    v.Id,
				Stock: v.Stock,
			})
		}
	}
	_, err := l.svcCtx.ProductRpc.SubtractStockRevert(ctx, &productclient.CheckAndSubtractStockReq{
		Data: stocks,
	})
	if err != nil {
		return fmt.Errorf("DeferedStockSubtractRevertProcessor revert stock failed: %+v : %w", err, asynq.SkipRetry)
	}

	return nil
}
